﻿<%@ WebHandler Language="C#" Class="ProcessingCycleReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;

/**
 * Description: 零件加工周期报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.4.15
 **/

public class ProcessingCycleReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSearchSqlString(JObject jObject)
    {
        string sql = @"
WITH aa AS
(
     SELECT t.productname,t.productdescription,t.workflowstepname,MEDIAN(t.dualtime) cycletime
     FROM
     (
         SELECT cci.productname,cci.productdescription,cci.containername,cci.qty,csr.lossqty,
                csr.workflowstepname,csr.dispatchdate,csr.checkdate,
                TRUNC(csr.checkdate-csr.dispatchdate,4) dualtime
         FROM containersteprecord csr
         LEFT JOIN containercurrentinfo cci ON cci.containerid = csr.containerid
         LEFT JOIN containerinstore cid ON cid.charg = cci.containername
         WHERE csr.dispatchdate IS NOT NULL AND csr.checkdate IS NOT NULL  AND cci.isinstore = 1 AND cid.createdate IS NOT NULL";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.factoryid ='{0}'", jObject["factoryid"].ToString());
        }
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        sql += @"
     ) t
     GROUP BY t.productname,t.productdescription,t.workflowstepname
)
SELECT aa.productname,aa.productdescription,workflowstepname,cycletime,bb.cycletimesum,n.hegelv,n.qty
FROM aa
LEFT JOIN (SELECT productname,SUM(cycletime) cycletimesum  FROM aa GROUP BY productname) bb ON aa.productname=bb.productname
LEFT JOIN 
(
     SELECT cci.productname,ROUND(SUM(cci.qty)/(SUM(cci.qty)+SUM(NVL(m.scrapqty,0))),2) * 100 || '%' hegelv,
            ROUND((SUM(cci.qty)+SUM(NVL(m.scrapqty,0))) / COUNT(cci.containerid),2) qty
     FROM containercurrentinfo cci 
     LEFT JOIN
     (
         SELECT t.containerid,SUM(t.scrapqty) scrapqty
         FROM 
         (
             SELECT cr.containerid,abs(cr.qty) scrapqty
             FROM CheckQtyChangeRecord cr
             LEFT JOIN containercurrentinfo cci ON cci.containerid = cr.containerid
             WHERE cr.isuse = 0 AND cr.changeqtytype = 2 AND cci.isinstore = 1";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.factoryid ='{0}'", jObject["factoryid"].ToString());
        }
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        sql += @"
             UNION ALL
             SELECT qhd.containerid,qhd.qty scrapqty
             FROM qtyhistorydetails qhd
             LEFT JOIN containercurrentinfo cci ON cci.containerid = qhd.containerid
             WHERE qhd.changeqtytype = 2 AND qhd.changecount = 1 AND cci.isinstore = 1";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.factoryid ='{0}'", jObject["factoryid"].ToString());
        }
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        sql += @"
         ) t 
         GROUP BY t.containerid
     ) M ON M.containerid = cci.containerid
     WHERE  cci.isinstore = 1 AND cci.qty > 0
     GROUP BY cci.productname
) N ON N.productname = aa.productname
ORDER BY aa.productname,aa.workflowstepname";
        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dtResult.Columns["productname"].Caption = "零件图号";
        dtResult.Columns["productdescription"].Caption = "零件名称";
        dtResult.Columns["workflowstepname"].Caption = "工序";
        dtResult.Columns["cycletime"].Caption = "工序周期（天）";
        dtResult.Columns["cycletimesum"].Caption = "工序总周期（天）";
        dtResult.Columns["hegelv"].Caption = "平均合格率";
        dtResult.Columns["qty"].Caption = "平均批次数量";
        ExportHelper.ExportExcel(dtResult, "零件加工周期报表");
    }
}